package com.quanyan.user.web;

import com.quanyan.api.APIResponse;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.user.model.vo.request.ReqNewsPraise;
import com.quanyan.user.model.vo.request.ReqUserPraise;
import com.quanyan.user.service.NewsPraiseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created by Administrator on 2016/11/16.
 */
@RestController
@RequestMapping("/api/user/praise/")
public class UserPraiseController {

    @Autowired
    private NewsPraiseService newsPraiseService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(UserPraiseController.class);

    @RequestMapping(value ="loadPraise" ,method = RequestMethod.POST)
    public APIResponse praiseList(@RequestBody ReqNewsPraise reqNewsPraise ,HttpServletRequest request){
        try {
            String userCookiesName = request.getHeader("userCookiesName");
            RedisKey redisKey = new RedisKey(userCookiesName, "");
            AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo)redisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
            Integer uid = null;
            if (appUserCacheInfo != null)
                uid = appUserCacheInfo.getUser_id();
            reqNewsPraise.setUid(uid);
            return  newsPraiseService.praiseList(reqNewsPraise);
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }

    @RequestMapping(value ="praise" ,method = RequestMethod.POST)
    public APIResponse praise(@RequestBody @Valid ReqUserPraise reqUserPraise ,HttpServletRequest request){
        int uid = (int)request.getAttribute("uid");
        reqUserPraise.setUid(uid);
        try {
                return  newsPraiseService.praise(reqUserPraise);
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }


    @RequestMapping(value ="cancelPraise" ,method = RequestMethod.POST)
    public APIResponse praiseCancel(@RequestBody @Valid ReqUserPraise reqUserPraise ,HttpServletRequest request){
        int uid = (int)request.getAttribute("uid");
        reqUserPraise.setUid(uid);
        try {
                return  newsPraiseService.praiseCancel(reqUserPraise);
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }


}
